<template>
  <div class="face-register-container">
    <el-card shadow="hover" title="人脸注册">
      <!-- 提示信息 -->
      <el-alert
        title="请确保光线充足，正对摄像头，露出完整面部"
        type="info"
        show-icon
        style="margin-bottom: 20px"
      ></el-alert>

      <!-- 摄像头预览区域 -->
      <div class="camera-container">
        <video
          ref="video"
          autoplay
          playsinline
          muted
          width="200"
          height="100"
          style="border: 1px solid #e6e6e6"
        ></video>
        <canvas
          ref="canvas"
          width="400"
          height="300"
          style="display: none"
        ></canvas>
      </div>

      <!-- 操作按钮 -->
      <div class="btn-group" style="margin-top: 20px">
        <el-button type="primary" @click="startCamera">开启摄像头</el-button>
        <el-button type="success" @click="captureFace" :disabled="!cameraActive"
          >拍摄人脸</el-button
        >
        <el-button type="danger" @click="stopCamera" :disabled="!cameraActive"
          >关闭摄像头</el-button
        >
      </div>

      <!-- 拍摄的人脸预览 -->
      <div v-if="faceImage" class="face-preview" style="margin-top: 20px">
        <el-image
          :src="faceImage"
          alt="人脸预览"
          width="200"
          height="150"
          style="border: 1px solid #e6e6e6"
        ></el-image>
        <el-button
          type="primary"
          @click="submitRegister"
          style="margin-top: 10px"
          >提交注册</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<script>
import { getFaceBindStatus, faceRegister } from "@/api/system/face"; // 导入后端接口

export default {
  name: "FaceRegister",
  data() {
    return {
      cameraActive: false, // 摄像头是否激活
      faceImage: "", // 拍摄的人脸图片（Base64）
      videoStream: null, // 摄像头流对象
    };
  },
  mounted() {
    // 页面加载时，检查用户是否已绑定人脸
    // this.checkFaceBindStatus();
  },
  beforeDestroy() {
    // 页面销毁时关闭摄像头
    this.stopCamera();
  },
  methods: {
    // 1. 检查人脸绑定状态
    // checkFaceBindStatus() {
    //   getFaceBindStatus().then((res) => {
    //     if (res.code === 200 && res.data === 1) {
    //       this.$message.error("您已绑定人脸，无需重复注册！");
    //       // 跳转回个人中心
    //       this.$router.push("/system/user");
    //     }
    //   });
    // },

    // 2. 开启摄像头
    startCamera() {
      const video = this.$refs.video;
      // 调用浏览器摄像头API（需HTTPS或localhost环境）
      navigator.mediaDevices
        .getUserMedia({ video: true })
        .then((stream) => {
          video.srcObject = stream;
          this.videoStream = stream;
          this.cameraActive = true;
          this.$message.success("摄像头开启成功！");
        })
        .catch((err) => {
          this.$message.error("摄像头开启失败：" + err.message);
          console.error("摄像头错误：", err);
        });
    },

    // 3. 拍摄人脸（转为Base64）
    captureFace() {
      const video = this.$refs.video;
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext("2d");

      // 将视频帧绘制到canvas
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      // 转为Base64（不含前缀data:image/jpeg;base64,）
      this.faceImage = canvas.toDataURL("image/jpeg").split(",")[1];
      this.$message.success("人脸拍摄成功！");
    },

    // 4. 关闭摄像头
    stopCamera() {
      if (this.videoStream) {
        this.videoStream.getTracks().forEach((track) => track.stop());
        this.videoStream = null;
        this.cameraActive = false;
        this.faceImage = "";
        this.$message.info("摄像头已关闭");
      }
    },

    // 5. 提交人脸注册（调用后端接口）
    submitRegister() {
      if (!this.faceImage) {
        this.$message.error("请先拍摄人脸！");
        return;
      }

      // 调用后端人脸注册接口
      faceRegister({ imageBase64: this.faceImage }).then((res) => {
        if (res.code === 200) {
          this.$message.success(res.msg);
          // 关闭摄像头并跳转
          this.stopCamera();
          this.$router.push("/system/user");
        } else {
          this.$message.error(res.msg);
        }
      });
    },
  },
};
</script>

<style scoped>
.face-register-container {
  padding: 20px;
}
.camera-container {
  display: flex;
  justify-content: center;
}
.btn-group {
  display: flex;
  justify-content: center;
  gap: 20px;
}
.face-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>
